package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Api(tags = "菜品接口")
@RequestMapping("/admin/dish")
@RestController
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("新增菜品")
    @PostMapping
    public Result add(@RequestBody DishDTO dishDTO){

        //添加到数据库
        System.out.println("dishDTO = " + dishDTO);
        dishService.add(dishDTO);

        //清楚缓存...
        cleanCache("dish_"+dishDTO.getCategoryId());


        return Result.success();
    }

    /**
     * 菜品分页查询
     * @param pageQueryDTO
     * @return
     */
    @ApiOperation("菜品分页")
    @GetMapping("/page")
    public Result page(DishPageQueryDTO pageQueryDTO){
        PageResult pageResult = dishService.page(pageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 批量删除菜品
     * @param ids
     * @return
     */
    @ApiOperation("批量删除菜品")
    @DeleteMapping
    public Result delete (@RequestParam List<Long> ids){
        dishService.delete(ids);


        cleanCache("dish_*");
        return Result.success();
    }


    /**
     * 根据ID查询菜品
     * @param id
     * @return
     */
    @ApiOperation("根据ID查询菜品")
    @GetMapping("/{id}")
    public Result findById(@PathVariable Long id){
        return Result.success(dishService.findById(id));
    }


    /**
     * 更新菜品
     * @param dto
     * @return
     */
    @ApiOperation("更新菜品")
    @PutMapping
    public Result update(@RequestBody DishDTO dto){
        dishService.update(dto);


        //直接删除掉所有的缓存分类数据即可
        cleanCache("dish_*");

        return Result.success();
    }

    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }



}
